#include "PipelineStateCache.h"

#include "CGICommandList.h"
#include "DynamicCGI.h"

namespace Alice
{
    static void InternalCreateGraphicsPipelineState(const FGraphicsPipelineStateInitializer& Initializer, EPSOPrecacheResult PSOPrecacheResult, bool bDoAsyncCompile, bool bPSOPrecache, FGraphicsPipelineState* CachedState, bool bInImmediateCmdList)
    {
        CachedState->mCGIGraphicsPipelineState=CGICreateGraphicsPipelineState(Initializer);
    };
    FGraphicsPipelineState* GetGraphicsPipelineState(CGICommandList& RHICmdList, const FGraphicsPipelineStateInitializer& Initializer, EApplyRendertargetOption ApplyFlags, bool bVerifyUse)
    {
#if PLATFORM_USE_FALLBACK_PSO
        checkNoEntry();
        return nullptr;
#else
        FGraphicsPipelineState* PipelineState = PipelineStateCache::GetAndOrCreateGraphicsPipelineState(RHICmdList, Initializer, ApplyFlags);
        //if (PipelineState && bVerifyUse && !Initializer.bFromPSOFileCache)
        //{
        //    PipelineState->Verify_IncUse();
        //}
        return PipelineState;
#endif
    }
    void SetGraphicsPipelineState(CGICommandList& inCGICommandList, const FGraphicsPipelineStateInitializer& Initializer, uint32 StencilRef, EApplyRendertargetOption ApplyFlags , bool bApplyAdditionalState)
    {
        FGraphicsPipelineState*pipelineState=GetGraphicsPipelineState(inCGICommandList,Initializer,ApplyFlags,false);
        inCGICommandList.SetGraphicsPipelineState(pipelineState,Initializer.mBoundShaderStateInput,0,false);
    }
    namespace PipelineStateCache
    {
        FGraphicsPipelineState* GetAndOrCreateGraphicsPipelineState(CGICommandList& RHICmdList, const FGraphicsPipelineStateInitializer& OriginalInitializer, EApplyRendertargetOption ApplyFlags)
        {
            static FGraphicsPipelineState*ret=nullptr;
            if(ret==nullptr)
            {
                ret=new FGraphicsPipelineState;
                InternalCreateGraphicsPipelineState(OriginalInitializer,EPSOPrecacheResult::Unknown,false,false,ret,true);
            }
            return ret;
        }
        CGIVertexDeclaration* GetOrCreateVertexDeclaration(const VertexDeclarationElementList& inVertexDeclarationElementList)
        {
            CGIVertexDeclaration* vertexDeclaration=RHICreateVertexDeclaration(inVertexDeclarationElementList);
            return vertexDeclaration;
        }
        bool PipelineStateCache::IsPSOPrecachingEnabled()
        {	
#if WITH_EDITOR
            // Disables in the editor for now by default untill more testing is done - still WIP
            return false;
#else
            return false;// GPSOPrecaching != 0 && GRHISupportsPSOPrecaching;
#endif // WITH_EDITOR
        }
    }
}
